<?php
namespace app\admin\controller\cms;

use app\common\controller\AdminBaseController;
use app\common\model\cms\ClassModel;
use app\common\model\cms\MoudleModel;
use app\common\model\SpecialItemModel;
use think\facade\Cache;

class ContentController extends AdminBaseController
{
    private $moudleModel;
    private $classModel;
    private $specialItemModel;
    /*
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->moudleModel = new MoudleModel();
        $this->classModel = new ClassModel();
        $this->specialItemModel = new SpecialItemModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $data = $this->pageList();
            return $data;
        }
        $moudleId = $this->request->param('moudle_id/d');
        $classList = $this->classModel->formatContentSelect($moudleId);
        $moudle = Cache::get('cms_moudle_'.$moudleId);
        $modelList = $this->moudleModel->where('status',1)->order('show_order asc')->select();
        $tplName = strtolower(str_replace('cms_table_','',$moudle['table_name'])).'_list';
        $this->assign('moudle',$moudle);
        $this->assign('modelList',$modelList);
        $this->assign('classList',$classList);
        return $this->fetch($tplName);
    }

    /**
     * 分页数据
     */
    public function pageList(){
        $moudleId = $this->request->param('moudle_id/d');
        $classId = $this->request->param('class_id/d');
        $data = ['total' => 0, 'rows' => []];
        if($moudleId<=0) return ['total' => 0, 'rows' => [], 'msg'=>'未指定模型'];
        $model = cms_model($moudleId);
        $pageSize = $this->request->param('pageSize/d'); //每页多少条
        $pageNumber = $this->request->param('pageNumber/d'); //当前页
        $sortName = $this->request->param('sortName', 'id'); //排序字段
        $sortOrder = $this->request->param('sortOrder', 'desc'); //升序降序
        $order = [$sortName => $sortOrder];
        $filter = $this->request->param("filter"); //搜索字段值 json
        $op = $this->request->param("op"); //搜索条件 json
        $filter = $filter ? $filter : [];
        try {
            $map[]=['moudle_id','=',$moudleId];
            if($classId>0){
                $class = $this->classModel->getList();
                $map[] = ['class_id','in',$class[$classId]['data_view']];
            }
            $data['total'] = $model->withSearch(['common'],[
                'common'=>[$filter, $op]
            ])->where($map)->count();
            if ($data['total'] > 0) {
                $list = $model->withSearch(['common'],[
                    'common'=>[$filter, $op],
                    'sort' => $order
                ])->where($map)->page($pageNumber, $pageSize)->select();
                $data['sql'] = $model->getLastSql();
                if (method_exists($model, '_formatList')) {
                    $list = $model->_formatList($list);
                }
                $data['rows'] = $list;
            }
        } catch (\Exception $e) {
            $data = ['total' => 0, 'rows' => [], 'err_msg' => $e->getMessage()];
        }
        return $data;
    }

    /**
     * 添加内容
     * @return mixed
     */
    public function add(){
        $moudleId = $this->request->param('moudle_id/d');
        if($moudleId<=0) $this->error('未找到指定模型！');
        $moudle = Cache::get('cms_moudle_'.$moudleId);
        if($this->request->isAjax()){
            try{
                $data = $this->request->param();
                $validRule = \FormBuild::formatRules($moudle['meta']);
                $this->validate($data,$validRule);
                $data['moudle_id'] = $moudleId;
                $data['admin_id'] = $this->loginInfo['id'];
                $info = cms_model($moudleId)->addData($data);
                if(!empty($data['special_ids'])){
                    $this->specialItemModel->addContent($moudleId,$info['id'],$data['special_ids']);
                }
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功！',null,$info);
        }
        $classList = $this->classModel->formatContentSelect($moudleId);
        $this->assign('classList',$classList);
        $tplName = strtolower(str_replace('cms_table_','',$moudle['table_name'])).'_add';
        return $this->fetch($tplName);
    }

    /**
     * 编辑内容
     * @return mixed
     */
    public function edit(){
        $moudleId = $this->request->param('moudle_id/d');
        $id = $this->request->param('id/d');
        $map[]=['id','=',$id];
        $info = cms_model($moudleId)->getInfo($map);
        $moudle = Cache::get('cms_moudle_'.$moudleId);
        if (empty($info)) $this->error('未找到数据！');
        if ($this->request->isAjax()) {
            try {
                $data = $this->request->param();
                $validRule = \FormBuild::formatRules($moudle['meta']);
                $this->validate($data,$validRule);
                $data['admin_id'] = $this->loginInfo['id'];
                $info = cms_model($moudleId)->editData($data);
                $this->specialItemModel->addContent($moudleId,$id,$data['special_ids']);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！', null, $info);
        }
        $classList = $this->classModel->formatContentSelect($moudleId);
        $this->assign('classList',$classList);
        $this->assign('info', $info);
        $tplName = strtolower(str_replace('cms_table_','',$moudle['table_name'])).'_edit';
        return $this->fetch($tplName);
    }

    /**
     * 删除数据
     */
    public function del(){
        try{
            $moudleId = $this->request->param('moudle_id/d');
            $id = $this->request->param('id');
            $this->specialItemModel->where('content_id',$id)->where('model_id',$moudleId)->delete();
            cms_model($moudleId)->delData($id);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    /**
     * 批量更新数据
     */
    public function multi()
    {
        $moudleId = $this->request->param('moudle_id/d');
        //ids: 1，3，5
        //params: status:1,is_boss=0
        if ($this->request->has('ids') && $this->request->has('params')) {
            try {
                $ids = $this->request->param('ids');
                $params = $this->request->param('params');
                cms_model($moudleId)->multi($ids, $params);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！');
        }
        $this->error('参数错误！');
    }
    /**
     * editable修改内容
     */
    public function editable(){
        header("Content-type: text/html; charset=utf-8");
        try{
            $moudleId = $this->request->param('moudle_id/d');
            $id = $this->request->param('pk');
            $name = $this->request->param('name');
            $value = $this->request->param('value');
            cms_model($moudleId)->where('id',$id)->setField($name,$value);
        }catch (\Exception $e){
            return response($e->getMessage(),40001);
        }
        return response('操作成功！');
    }

}